#include "mygraphview.h"
#include <iostream>
#include <QScrollBar>
#include <QGraphicsItem>
#include "meshitem.h"
#include "config.h"

MyGraphView::MyGraphView(QObject *parent)
{
  //  this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

   // this->verticalScrollBar()->show();
   // this->verticalScrollBar()->setMinimum(-1000);
   // this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scale(1, -1);

    selected_item = NULL;
}

void MyGraphView::mouseMoveEvent(QMouseEvent *event)
{
    if (pan_)
    {
        horizontalScrollBar()->setValue(horizontalScrollBar()->value() - (event->x() - pan_start_x_));
        verticalScrollBar()->setValue(verticalScrollBar()->value() - (event->y() - pan_start_y_));
        pan_start_x_ = event->x();
        pan_start_y_ = event->y();
        event->accept();
        return;
    }
    event->ignore();
}

void MyGraphView::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::RightButton)
    {
        pan_ = true;
        pan_start_x_ = event->x();
        pan_start_y_ = event->y();
        setCursor(Qt::ClosedHandCursor);
        event->accept();
        return;
    }

    if (event->button() == Qt::LeftButton)
    {
        MeshItem *it = dynamic_cast <MeshItem * > (this->scene()->itemAt(mapToScene(event->pos()),this->transform()) );
        if (it)
        {
            it->select();


            if ( selected_item != NULL)
            {
                this->selected_item->select();

            }

            this->selected_item = it;
            this->scene()->update(this->sceneRect());
            emit meshItemSelected(it);
        }
    }

    event->ignore();
}

void MyGraphView::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::RightButton)
    {
        pan_ = false;
        setCursor(Qt::ArrowCursor);
        return;
    }
}

void MyGraphView::wheelEvent(QWheelEvent *event)
{

    setTransformationAnchor(QGraphicsView::AnchorViewCenter);

    if ( event->delta() > 0)
        this->scale(Config::zoomFactor(),Config::zoomFactor());
    else
        this->scale(1.0/Config::zoomFactor(), 1.0/Config::zoomFactor());
}
